package com.oneonefive.educationsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oneonefive.educationsystem.domain.Semester;
import com.oneonefive.educationsystem.dto.Result;
import com.oneonefive.educationsystem.service.SemesterService;
import com.oneonefive.educationsystem.mapper.SemesterMapper;
import com.oneonefive.educationsystem.utils.ReflectUtil;
import com.oneonefive.educationsystem.utils.Constant;
import com.oneonefive.educationsystem.utils.StateChangeUtil;
import com.oneonefive.educationsystem.vo.SemesterVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


@Service
public class SemesterServiceImpl extends ServiceImpl<SemesterMapper, Semester>
    implements SemesterService{

    @Resource
    SemesterMapper semesterMapper;
    @Override
    public Result semesterList(SemesterVo semesterVo) {
        QueryWrapper<Semester> wrapper = new QueryWrapper<>();
        ReflectUtil<Semester> checkNullUtil = new ReflectUtil<>();
        checkNullUtil.swaggerCheck(semesterVo,wrapper,Semester.class);
        long total = semesterMapper.selectList(wrapper).size();
        wrapper.orderByDesc("state");
        wrapper.orderByDesc("term");
        if (semesterVo.getPage() != null) {
            int start = (semesterVo.getPage() - 1) * 10;
            wrapper.last("limit " + start + ",10");
        }

        List<Semester> semesters = semesterMapper.selectList(wrapper);
        List<SemesterVo> resList = getResVo(semesters);
        return Result.ok(resList, total);
    }

    public List<SemesterVo> getResVo(List<Semester> list) {
        List<SemesterVo> resList = new ArrayList<>();
        for (Semester semester : list) {
            SemesterVo semesterVo = new SemesterVo();
            BeanUtils.copyProperties(semester, semesterVo);
            semesterVo.setStateString(StateChangeUtil.semesterChange(semester.getState()));
            resList.add(semesterVo);
        }
        return resList;
    }

    @Override
    public Result legitimacy(Semester semester) {
        if (!Pattern.matches(Constant.TERM_REGEX, semester.getTerm())) {
            return Result.fail("输入的学期不符合格式");
        }
        if (semester.getWeek() < 18 || semester.getWeek() > 20) {
            return Result.fail("一学期的周次在18~20");
        }
        return Result.ok();
    }

}




